package com.itheima.aspect;


import com.itheima.anno.AutoFill;
import com.itheima.common.AutoFillConstant;
import com.itheima.enums.OperationType;
import com.itheima.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Map;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {


    @Pointcut("execution(* com.itheima.mapper.*.*(..)) && @annotation(com.itheima.anno.AutoFill)")
    public void autoFillPointCount() {
        
    }

    @Before("autoFillPointCount()")
    public void autoFill(JoinPoint joinPoint) {
        
        log.info("开始填充公共字段");

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();  // 获取方法的名称

        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);

        OperationType operationType = autoFill.value();

        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }

        Object entity = args[0];

        LocalDateTime now = LocalDateTime.now();

        Map<String,Object> map = ThreadLocalUtil.get();
        Long uid = (Long) map.get("uid");


        Long currentId = uid;

        try {
            // 4.根据当前不同给的操作类型 为 对应属性通过 反射来 进行 赋值
            if (operationType == OperationType.INSERT) {
                // 如通是插入的话 那么 4个字段 都需要赋值

                // TODO AOP + 反射
                Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                setCreateTime.invoke(entity, now);
                setCreateUser.invoke(entity, currentId);
                setUpdateTime.invoke(entity, now);
                setUpdateUser.invoke(entity, currentId);


            } else if (operationType == OperationType.UPDATE) {
                // 如果是更新操作 那么只需要 给两个 公共字段赋值

                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);


                setUpdateTime.invoke(entity, now);
                setUpdateUser.invoke(entity, currentId);


            }
        } catch (Exception e) {
            e.printStackTrace();

        }

    }

}
